<template>
	<view class="container">
		<view class="allTips" v-if="showEnd">-已显示全部会话信息-</view>
		<view class="chatBox">
			<view v-for="(item,index) in chatLogList" :class="[item.role==='user'?'self-msg':'other-msg',]">
				<view v-if="item.type=='text'" v-html="item.message"></view>
				<view v-if="item.type=='img'" @tap="previewImg(item.message)">
					<image v-if="item.message" :src="item.message"  mode="widthFix" style="width: 30vw;"></image>
					<image v-else src="/static/image/imgFail.png" mode="widthFix" style="width: 30vw;"></image>
				</view>
			</view>
		</view>
		<!-- 输入框 -->
		<view class="input-area">
			<view class="textareaBox">
				<textarea v-model="askText" maxlength="-1" id="textarea" placeholder="请输入您的问题~"
					:style="'height:' + boxHeight +'rpx'" @linechange="autoResize"></textarea>
			</view>
			<view class="iconfont icon-24gf-picture" style="font-size: 50rpx;" @tap="sendImg()">
			</view>
			<view class="iconfont icon-fasong" style="font-size: 50rpx;" @tap="sendMsg()">
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				askText: "",
				boxHeight: '80', // 初始高度为自动
				chatLogList: [
					// {
					// 	role: "user",
					// 	type: "text",
					// 	content: "你好"
					// },
					// {
					// 	role: "user",
					// 	type: "img",
					// 	content: "https://qw.lvd8.cn/message/1000081696918216.png"
					// },
					// {
					// 	role: "assistant",
					// 	type: "text",
					// 	content: "你好和我我我我我2我我我我我"
					// },
					// {
					// 	role: "user",
					// 	type: "text",
					// 	content: "你好"
					// },
					// {
					// 	role: "user",
					// 	type: "img",
					// 	content: "https://qw.lvd8.cn/message/1000081696918216.png"
					// },
					// {
					// 	role: "assistant",
					// 	type: "text",
					// 	content: "你好和我我我我我2我我我我我"
					// }
				],
				webSocket: null, //aiSocket对象
				endResScript: "",
				page:1,
				showEnd:false
			}
		},
		//上拉历史记录
		onPullDownRefresh(){
			  console.log('下拉刷新onPullDownRefresh');
			  this.page=this.page+1
			  this.getLogs()
			  setTimeout(function(){
				uni.stopPullDownRefresh()
			  },1000);
		},
		onLoad() {
			this.getLogs()
		},
		onShow() {
			this.connGptFun()
			this.page=1
			this.showEnd=false
		},
		onHide() {
			this.webSocket.close()
		},
		methods: {
			async getLogs(){
				const data = await this.$http('/appapi/message/get_log',{
					page:this.page
				})
				console.log("获取历史记录：=====================")
				console.log(data)
				if(this.page==1){
					this.chatLogList=data
					this.scrollToBottom();
				}else if(data.length==0){
					//已全部显示完
					console.log("已全部显示完")
					this.showEnd=true
				}else{
					console.log("做拼接的部分")
					let arr = data;  
					  
					for(let i = arr.length-1; i >=0; i--) {  
					 console.log("第"+i+1+"条数据====")
					  console.log(arr[i])
					  this.chatLogList.unshift(arr[i])
						//滑动滚条
					}  
				}
				
				
			},
			connGptFun() {
				var that = this
				this.webSocket = wx.connectSocket({ //链接wss服务
					url: "wss://qw.lvd8.cn/ws",
					success: () => {
						console.log("wss服务链接成功");
					}
				})
				this.webSocket.onError((e) => {

				})
				// 打开websocket
				this.webSocket.onOpen((e) => {
					// uni.showLoading({
					// 	title: "加载中",
					// 	mask: true
					// })

					this.connectionAiSocket(e)
				})
				//监听消息
				this.webSocket.onMessage((e) => {
					this.listeningForMessage(e)
				})

				this.webSocket.onClose((e) => {
					//this.connSocket(e)
				})
			},
			connSocket() {
				var that = this
				this.webSocket = wx.connectSocket({ //链接wss服务
					url: "wss://qw.lvd8.cn/ws  ",
					success: () => {
						console.log("wss服务链接成功");
					}
				})
				this.webSocket.onError((e) => {

				})
				// 打开websocket
				this.webSocket.onOpen((e) => {
					// uni.showLoading({
					// 	title: "加载中",
					// 	mask: true
					// })

					this.connectionAiSocket(e)
				})
				//监听消息
				this.webSocket.onMessage((e) => {
					this.listeningForMessage(e)
				})
				this.webSocket.onClose((e) => {

				})
			},
			connectionAiSocket(e) {
				var json = JSON.stringify({
					"type": "qw_login",
					"openid": uni.getStorageSync("token")
				})
				this.webSocket.send({
					data: json,
				})
				this.sendPing();
			},
			sendPing() {
				this.webSocket.send({
					data: "ping",
				})
				setTimeout(() => {
					this.sendPing();
				}, 30000);
			},
			//监听aiSocket message事件
			listeningForMessage(e) {
				var that = this
				if (e.data == "pong") {
					return;
				}
				let resData = JSON.parse(e.data)
				let result = JSON.parse(resData.data[0])
				//添加客服回复新消息
				this.chatLogList.push({
					role: "assistant",
					type: result.type,
					message: result.message
				});
				// 添加新消息后，滚动对话区域到底部
				this.scrollToBottom();
			},
			autoResize(e) {
				console.log(e.detail.height);
				this.boxHeight = 50 + e.detail.height
			},
			scrollToBottom() {
				// 使用uni.createSelectorQuery选择器来获取对话区域元素并进行滚动操作
				uni.createSelectorQuery()
					.in(this)
					.select('.chatBox')
					.boundingClientRect((rect) => {
						console.log("滚动条操作")
						console.log(rect)
						uni.pageScrollTo({
							scrollTop: rect.height // 滚动到底部，rect.height是元素的高度
						});
					})
					.exec();
			},
			previewImg(img) {
				console.log("previewImg")
				uni.previewImage({
					current: img,
					urls: [img]
				})
			},
			//发送图片
			sendImg() {
				console.log("选择发送图片")
				// 发送图片   
				// url   https://qw.lvd8.cn/appapi/message/up_img
				// 参数
				// token  （string） 用户验证
				// img      （file）    发送的图片文件
				var that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						//发送请求
						let tmpImg = res.tempFilePaths[0]
						console.log(typeof(tmpImg))
						that.addImgMsg(tmpImg)
					},
					fail: (err) => {
						// 处理选取图片失败的情况
						console.error('选择图片失败：', err);
					},
				});
			},
			addImgMsg(tmpImg) {
				var that = this
				console.log("addImgMsg" + tmpImg)
				//https://qw.lvd8.cn/appapi/message/up_img
				uni.uploadFile({
					url: 'https://qw.lvd8.cn/appapi/message/up_img',
					filePath: tmpImg,
					name: 'img',
					header: {
						'content-type': 'multipart/form-data',
					},
					formData: {
						token: uni.getStorageSync('token')
					},
					success: function(res) {
						console.log("发送图片回调")
						console.log(res.data)
						let result = JSON.parse(res.data)

						//新增图片类会话
						//添加用户新消息
						that.chatLogList.push({
							role: "user",
							type: "img",
							message: result.msg
						});
						// 添加新消息后，滚动对话区域到底部
						that.scrollToBottom();
					},
					fail(err) {
						console.log(err)
						uni.showToast({
							title: '发送图片失败',
							icon: 'success',
							duration: 2000,
						});
					}
				})

			},
			//发送文本
			sendMsg() {
				//非空校验
				if (this.askText == "") {
					uni.showToast({
						title: "说点什么吧",
						icon: "none"
					})
					return
				}

				//添加用户新消息
				this.chatLogList.push({
					role: "user",
					type: "text",
					message: this.askText
				});
				var getScriptData = {
					type: "dialogue",
					to: "qw.lvd8.cn",
					message: this.askText
				}
				let tempStr = JSON.stringify(getScriptData)
				this.webSocket.send({
					data: tempStr,
				})
				// 添加新消息后，滚动对话区域到底部
				this.scrollToBottom();

				this.askText = ""
			}
		}
	}
</script>

<style lang="scss" scoped>
	.allTips{
		text-align: center;color: #c7c7c7;font-size: 25rpx;
	}
	.container {
		min-height: 100vh;
		background-color: #F6F7F8;
		box-sizing: border-box;
	}

	#textarea {
		resize: none;
		overflow-y: scroll;
	}

	.refreshIcon {
		font-size: 50rpx;
		padding: 10rpx;
	}

	.input-area {
		background-color: #fff;
		width: 100vw;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		position: fixed;
		gap: 20rpx;
		bottom: 0;
		max-height: 60vh;
		overflow: scroll;
	}

	.chatBox {
		display: flex;
		flex-direction: column;
		padding: 0 20rpx 130rpx 20rpx;
	}

	.self-msg {
		background-color: #F8C4D4;
		padding: 16px;
		align-self: flex-end;
		border-radius: 8px;
		color: #fff;
		margin: 15rpx 0;
		max-width: 70%;
	}

	.other-msg {
		background-color: #ffffff;
		padding: 16px;
		align-self: flex-start;
		border-radius: 8px;
		color: #4f4f4f;
		margin: 15rpx 0;
		max-width: 70%;
	}

	.textareaBox {
		width: 500rpx;
		background-color: #f0f0f0;
		border-radius: 20rpx;
		overflow: hidden;
		padding: 10rpx;

		textarea {
			width: 100%;
		}

		.textareaStyle {
			resize: none;
			width: 100%;
			border: 1px solid #ccc;
			padding: 10px;
			overflow-y: hidden;
		}
	}
</style>